<?php
//QQ496631085
namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Wxsdk;
use think\Db;


class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    // protected $layout = '';
    public function  _initialize(){
    	$this->appId = 'wx63c391768f362ca80';  //wxe6747dc052817254
        $this->appSecret = '512ec5eb6117b86bcaccf3f10b45edc2';  //
        if(!empty($this->request->get('o'))){
             session('copenid',$this->request->get('o'));
        }
        $this->Wxsdk = new Wxsdk();
        $this->_domain = $this->Wxsdk->domain();


        if(empty(session('diyici_url'))){
            session('diyici_url',$this->request->action());
        }

        $share['sharelink'] = $this->_domain.'/index/index/about';//分享链接
        $share['title'] = config('site.name');//分享标题
        $share['sharedesc'] = "文字介绍！QQ496631085";
        $share['icourl'] = $this->_domain."/assets/img/ico.png";

        $this->getsign = $this->Wxsdk->getSignPackage();
        $this->view->assign('appid',$this->appId );
        $this->view->assign('wxsign',$this->getsign);
        $this->view->assign('site',config('site'));//公共的 网站配置
       
        $this->view->assign('share',$share);
        // if(!empty($_SERVER['HTTP_REFERER'])){
        //     $this->redirect($_SERVER['HTTP_REFERER']);
        // }
    }

    //判断是否微信用户 已经手机注册  ，没有注册请注册才能使用
    public function isRegUser(){
        if(empty($this->get_openid_user(session('user.openid'))['tel'])){
            $this->redirect($this->_domain.'/index/index/registered');
            exit();
        }
    }


    public function index(){
        
        return $this->view->fetch();  
    }

    //关于我们
    public function about(){
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    //联系我们
    public function contact(){
        $this->islogin();
        $this->isRegUser();
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }


    //用户页面
    public function membercentre(){
        $this->islogin();
        $this->isRegUser();

        $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    //注册页面
    public function registered(){
        $this->islogin();

        if(!empty($this->get_openid_user(session('user.openid'))['tel'])){
            $this->redirect($this->_domain.'/index/index/membercentre');
            exit();
        }

        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    //报修提交页面
    public function repair(){
        $this->islogin();
        $this->isRegUser();
        $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
        
    }

    //测试无用
    public function baoxiut(){
        $this->islogin();
        // $this->isRegUser();
        $id = $this->request->param('id');

        if(!empty($id)){
            $data = Db::name('baoxiu')->where('id',$id)->find();
            if(!$data){
            echo '<script>alert("此链接已被删除"); window.close();</script>';
            		exit();
        	}
        	$this->view->assign('data',$data);
	        $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
	        // $this->view->assign('site',config('site'));
	        return $this->view->fetch();  
        }
        
    }

    //报修状态页面 和评价页面
    public function baoxiu(){
      	$this->islogin();
        // $this->isRegUser();
        $id = $this->request->param('id');

        if(!empty($id)){
            $data = Db::name('baoxiu')->where('id',$id)->find();
            if(!$data){
            echo '<script>alert("此链接已被删除"); window.close();</script>';
            		exit();
        	}
        	$this->view->assign('data',$data);
	        $this->view->assign('wxuser',$this->get_openid_user($data['openid']));
	        // $this->view->assign('site',config('site'));
	        return $this->view->fetch();  
        }
    }

    //管理员推送的模板消息
    public function tuisong(){
        $id = $this->request->param('id');
        if($id){
           $data = Db::name('message_template')->where('id',$id)->find();
        }else{
            echo '<script>alert("此网页已被删除"); window.close();</script>';
        }

        $this->view->assign('data',$data);
        // $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    //建议状态页面  和评价页面
    public function jianyi(){
        $id = $this->request->param('id');
        if($id){
           $data = Db::name('suggest')->where('id',$id)->find();
           	$this->view->assign('data',$data);
	        $this->view->assign('wxuser',$this->get_openid_user($data['openid']));
	        // $this->view->assign('site',config('site'));
	        return $this->view->fetch(); 
        }else{
            echo '<script>alert("没有此网站"); window.close();</script>';
        }

 
    }
    
    ////建议提交页面
    public function suggestions(){
        $this->islogin();
        $this->isRegUser();
        $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
        // $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }


    //
    public function wxindex()
    {	
        if(!empty($this->request->get('o'))){
             session('copenid',$this->request->get('o'));
        }
    	
    }




    private function islogin(){
        //验证是否登录过，如果没有登录就跳转
         if(empty(session('user.openid'))){
                $this->getUserOpenId();
            // $this->redirect('/index/index/me');
                exit();
            }else{
                echo " ";
                // dump(session('openid'));
            }

    }

    public function getUserOpenId(){
        if(!empty($_SERVER['HTTP_REFERER']))
        file_put_contents('tiaozhuan.txt', $_SERVER['HTTP_REFERER'].'\r\n',FILE_APPEND);

        $num1 = file_get_contents('num1.txt');
        file_put_contents('num1.txt',++$num1);

       if(empty($this->request->get('code'))){
            $this->getBaseInfo();
            exit();
        }

        $code = $this->request->get('code');

        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code ";
        //3.拉取用户的openid
        $num = file_get_contents('num2.txt');
        file_put_contents('num2.txt',++$num);

        $res = file_get_contents($url);

        $data = json_decode($res,true);
        if(!empty($data['access_token']) && !empty($data['openid'])){
            $this->access_token=$data['access_token'];
            $this->refresh_token=$data['refresh_token'];
            
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN"; 
            $userInfo = file_get_contents($url);
            $user_res = json_decode($userInfo,true);
            // echo $userInfo;
            session('user',$user_res);
            $this->add_Wxuser($user_res);
            // dump($user_res);
            //获取都用户信息然后判断是否新用户 存表

            session('openid',$user_res);
              if(!empty(session('diyici_url'))){
                    $this->redirect($this->_domain.'/index/index/'.session('diyici_url'));//登录后跳转页面
                 }else{
                    $this->redirect($this->_domain.'/index/index/index');
                 }

            // if(empty($user['tel']) || empty($user['name'])){ //如果手机
                    
            //         $this->redirect($this->_domain.'/index/index/index');
            //         // $this->redirect($this->_domain.'/index/index/userdata');
                 
            // }else{
               
            // }
            

            

        }else{
            dump($data);
            // $this->getUserOpenId();
            exit();
        }
    }


        //获取code
    public function getBaseInfo(){
        //1.获取到code        
        $num = file_get_contents('getBaseInfo.txt');
        file_put_contents('getBaseInfo.txt',++$num);

        $redirect_uri=urlencode($this->_domain."/index/index/getUserOpenId");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=xiaohe#wechat_redirect";
        $this->redirect($url);
        exit();
    }



    public function add_Wxuser($user){
        //在你的数据库 添加用户信息
        // session('user',$user);
        // dump($this->openid);
        $res_user=Db::name('wxuser')->where('openid',$user['openid'])->find();

        $db_data['nickname'] = base64_encode($user['nickname']);
        $db_data['head_url'] = $user['headimgurl'];
        $db_data['openid'] = $user['openid'];
       
        // $db_data['copenid'] = $user['_copenid'];
        $db_data['sex'] = $user['sex'];
        $db_data['updatetime']=time();

        if(!$res_user) {
            //用户不存在，创建用户，没有详细信息
            $db_data['copenid'] =  session('copenid');//看需不需要修改推荐人
            
            $db_data['createtime']=time();
            //再次查询3-2新增 第几个进入
            $max_sort=Db::name('wxuser')->max('sort');
            // dump($manx_sort);
            if(!$max_sort){
                $max_sort = 0;//防止数据库清空默认为1
            }
            $db_data['sort'] = ++$max_sort;

            // if($db_data['sort']>3000){
            //     $db_data['sort']=1;   //超过300份奖品就不给序号
            // }
            // exit($max_sort);

            // if($this->isZhongJiang($db_data['sort'])){   //如果中奖
            //     $res_cdk = Db::name('cdk')->find();    //查询cdk
            //     if(!empty($res_cdk['cdk'])){           //还有cdk
            //         $db_data['cdk'] = $res_cdk['cdk'];    //赋值
            //         //然后在删除
            //         $res_del = Db::name('cdk')->where('cdk',$res_cdk['cdk'])->delete();//
            //         if(!$res_del){
            //             file_put_contents('cdkdel_error', $res_cdk['cdk']);
            //         }
            //     }//else  就没有ckd了

            // }
            $row = Db::name('wxuser')->insert($db_data);
        }else{ //修改头像地址和昵称以防用户修改

            $row = Db::name('wxuser')->where('openid',$user['openid'])->update($db_data);
            // if($row!=null)
                // echo "更新个人资料成功";
        }   
    }


        //查询openid的信息
    private function get_openid_user($openid){
        $data = Db::name('wxuser')->where('openid',$openid)->find();
        return $data;
    }












}
